package com.algo.proto.client;

import java.util.Random;

import com.algo.proto.DataInfo;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class ProtoClientHandler extends SimpleChannelInboundHandler<String> {

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {

	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		for (int i = 0; i < 10; i++) {
			int randomNum = new Random().nextInt(3);

			DataInfo.AbstractObject object = null;

			switch (randomNum) {
			case 0:
				object = DataInfo.AbstractObject.newBuilder()
							.setObjectType(DataInfo.AbstractObject.ObjectType.STUDENT)
							.setStudent(DataInfo.Student.newBuilder()
									.setName("zhangsan")
									.setAge(28)
									.setAddress("上海")
									.build()
							)
							.build();
				break;
			case 1:
				object = DataInfo.AbstractObject.newBuilder()
							.setObjectType(DataInfo.AbstractObject.ObjectType.CAR)
							.setCar(DataInfo.Car.newBuilder()
									.setBrand("宝马")
									.setPrice(310000.9)
									.build()
							)
							.build();
				break;
			case 2:
				object = DataInfo.AbstractObject.newBuilder()
							.setObjectType(DataInfo.AbstractObject.ObjectType.BALL)
							.setBall(DataInfo.Ball.newBuilder()
									.setCategory("篮球")
									.setColor("红色")
									.build()
							)
				.build();
				break;
			default:
				break;
			}
			
			ctx.channel().writeAndFlush(object);
			
			Thread.sleep(500);
		}
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
		cause.printStackTrace();
		ctx.close();
	}

}